/**
 * 加载运行器
 */
import unpack from "../unpack";
import path from "path";
import rewrite from "../rewrite";
import fs from "fs";

export default class loadRun{
    // 运行的打包的文件
    static runPack = "";
    static packData = {};
    static config = {};
    // 需要运行的打包文件里面的某个项目
    static mainPack = "";
    static mainFile = "";
    // 包名
    static mainName = "";

    // 进行插柱
    static insertColumn (){
        rewrite.setPackData(this.packData);
        rewrite.setConfig(this.config);
        rewrite.setRunPack(this.runPack);
        rewrite.insertColumn_findPath();
        rewrite.insertColumn_createReadStream();
        rewrite.insertColumn_existsSync();
        rewrite.insertColumn_lstatSync();
        rewrite.insertColumn_readFileSync();
        rewrite.insertColumn_readdirSync();
        rewrite.insertColumn_statSync();
        rewrite.insertColumn_watchFile();
        rewrite.insertColumn_read();
        rewrite.insertColumn_open();
    }

    // 运行这个打的包
    static async run(filePath:string) {
        if(fs.existsSync(filePath)){
            this.runPack = path.join(filePath);
        }else{
            this.runPack = path.join(process.cwd(),filePath);
        }
        let {data,config,mainPackage} = await unpack.start(this.runPack);

        this.packData = data;
        this.config = config;
        this.mainPack = mainPackage?path.join(process.cwd(),mainPackage):undefined;
        this.insertColumn();

        // 把路径补全
        Object.keys(this.packData).forEach(e=>{
            this.packData[path.join(process.cwd(),e)]=this.packData[e];
            delete this.packData[e];
        });
        // 默认获取path最短的package.json包最为运行的主包
        if(this.mainName){
            this.mainPack = undefined;
            Object.keys(this.packData).forEach(e=>{
                if(e.endsWith("package.json")){
                    // 判断名称
                    let data = JSON.parse(this.packData[e]);
                    if(data.name === this.mainName){
                        this.mainPack = e;
                    }
                }
            })
        }
        if(this.mainPack === undefined){
            console.log("没找到项目配置文件");
            return
        }
        this.mainFile = this.parsPackage(this.mainPack,this.packData[this.mainPack]);
        if(!this.mainFile){
            console.log("找不到入口文件,请准确设置package.json中的main字段指向的文件");
            return
        }

        if(!this.packData[this.mainFile]){
            console.log("未找到入口模块",this.mainFile);
            return
        }
        try{
            // 开始加载主文件
            require(this.mainFile);
        }catch(err){
            console.log("项目运行出现未捕捉的异常");
            console.log(err.message);
            console.log(err);
        }
    }

    // 解析出package文件
    static parsPackage(prefix, content){
        let pack = JSON.parse(content.toString());
        if(!pack["main"]) return undefined;
        return  path.join(path.parse(prefix).dir,pack["main"]);
    }

    static getFileConfig(id){
        return this.config[id.replace(process.cwd(),"")]
    }
}